<template>
  <canvas canvas-id="mychart-area" :id="canvasId" :style="{ width: canvasWidth, height: canvasHeight }"></canvas>
</template>

<script>
export default {
  props: {
    canvasId: {
      type: String,
      default: 'mychart-area'
    },
    canvasWidth: {
      type: String,
      default: '100%'
    },
    canvasHeight: {
      type: String,
      default: '400px'
    }
  },
  methods: {
    initChart(callback) {
      // 返回 promise 供外部调用
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        // 微信小程序环境中
        this.$nextTick(() => {
          this.createSelectorQuery()
            .select(`#${this.canvasId}`)
            .fields({ node: true, size: true })
            .exec(res => {
              const canvas = res[0].node;
              const width = res[0].width;
              const height = res[0].height;
              const chart = callback(canvas, width, height);
              resolve(chart);
            });
        });
        // #endif

        // #ifdef H5
        this.$nextTick(() => {
          const canvas = this.$refs.myChart;
          const width = canvas.clientWidth;
          const height = canvas.clientHeight;
          const chart = callback(canvas, width, height);
          resolve(chart);
        });
        // #endif
      });
    }
  }
};
</script>

<style scoped>
canvas {
  display: block;
}
</style>
